<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use fast\Tree;
use app\admin\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as XlsxWriter;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 项目管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Goods
     */
    protected $model = null;
    protected $modelValidate = true;
    protected $selectpageFields = "id,title,goods_no";
    protected $noNeedRight = ['export'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Goods;


        $tree = Tree::instance();
        $tree->init(collection((new \app\admin\model\goods\GoodsCategory())->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $goodsCategoryList = $tree->getTreeArray(0);
        $this->view->assign("goodsCategoryList", $goodsCategoryList);

        $biaobenrongqiList = (new \app\admin\model\goods\BiaobenRongqi())->where('deletetime',null)->select();
        $this->view->assign("biaobenrongqiList", $biaobenrongqiList);

        $biaobentypeList = (new \app\admin\model\goods\BiaobenType())->select();
        $this->view->assign("biaobentypeList", $biaobentypeList);

        $commissionTypeList = [['id'=>10,'title'=>'默认比例'],['id'=>20,'title'=>'固定金额']];
        $this->view->assign("commissionTypeList", $commissionTypeList);

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where('type',10)
            ->order($sort, $order)
            ->with(['biaobenType'])
            ->paginate($limit);
        foreach($list as &$item){
            $item['goods_category'] = \app\admin\model\goods\GoodsCategory::where('id','in',$item['goods_category_id'])->select();
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        
        // $params['num'] = count(explode(',',$params['biaoben_rongqi_id']));
        $params['pinyin_title'] = \fast\Pinyin::get($params['title']);
        $params['goods_category_id'] = implode(',',$params['goods_category_id']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params = $this->preExcludeFields($params);
        // $params['num'] = count(explode(',',$params['biaoben_rongqi_id']));
        $params['pinyin_title'] = \fast\Pinyin::get($params['title']);
        $params['goods_category_id'] = implode(',',$params['goods_category_id']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function batchedit()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->where('type','=',$params['type'])->where("FIND_IN_SET({$params['biaoben_rongqi_id']}, biaoben_rongqi_id)")->update(['image'=>$params['image']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function import(){
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        ini_set('memory_limit', '512M');
        $filePath = ROOT_PATH . DS . 'public' . DS . parse_url($file)['path'];
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
        $updatecount = 0;
        $skip = 0;
        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];

        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }

            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }

                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    if(isset($row['goods_category_id']) && !empty($row['goods_category_id'])){
                        $goods_category = \app\admin\model\goods\GoodsCategory::where('title','in',$row['goods_category_id'])->column('id');
                        if(empty($goods_category)){
                            $skip++;
                            throw new Exception("第{$currentRow}行数据保存失败,项目分类不存在", 1);
                            continue;
                        }
                        $row['goods_category_id'] = implode(',',$goods_category);
                    }

                    if(isset($row['biaoben_type_id']) && !empty($row['biaoben_type_id'])){
                        $biaoben_type = \app\admin\model\goods\BiaobenType::where('title','in',$row['biaoben_type_id'])->column('id');
                        if(empty($biaoben_type)){
                            $skip++;
                            throw new Exception("第{$currentRow}行数据保存失败,标本类型不存在", 1);
                            continue;
                        }
                        $row['biaoben_type_id'] = implode(',',$biaoben_type);
                    }

                    if(isset($row['biaoben_rongqi_id']) && !empty($row['biaoben_rongqi_id'])){
                        $biaoben_rongqi = \app\admin\model\goods\BiaobenRongqi::where('title','in',$row['biaoben_rongqi_id'])->column('id');
                        if(empty($biaoben_rongqi)){
                            $skip++;
                            throw new Exception("第{$currentRow}行数据保存失败,标本容器不存在", 1);
                            continue;
                        }
                        $row['biaoben_rongqi_id'] = implode(',',$biaoben_rongqi);
                    }
                    $goods = $this->model->where('goods_no',$row['goods_no'])->find();
                    if($goods){
                        $goods->allowField(true)->save($row,['goods_no'=>$row['goods_no']]);
                        $updatecount ++;
                        continue;
                    }

                    try {
                        $res = $this->model->saveAll([$row]);
                        if(!$res){
                            $this->error("第{$currentRow}行数据保存失败");
                        }
                        $insert[] = $row;
                    } catch (\Exception $e) {
                        throw new Exception("第{$currentRow}行数据保存失败", 1);
                    }
                    
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert && !$updatecount) {
            $this->error(__('No rows were updated'));
        }

        // try {
        //     //是否包含admin_id字段
        //     $has_admin_id = false;
        //     foreach ($fieldArr as $name => $key) {
        //         if ($key == 'admin_id') {
        //             $has_admin_id = true;
        //             break;
        //         }
        //     }
        //     if ($has_admin_id) {
        //         $auth = Auth::instance();
        //         foreach ($insert as &$val) {
        //             if (empty($val['admin_id'])) {
        //                 $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
        //             }
        //         }
        //     }
        //     $this->model->saveAll($insert);
        // } catch (PDOException $exception) {
        //     $msg = $exception->getMessage();
        //     if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
        //         $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
        //     };
        //     $this->error($msg);
        // } catch (Exception $e) {
        //     $this->error($e->getMessage());
        // }
        $message = '';
        if(count($insert) > 0){
            $message .= "导入: " . count($insert) . " 条";
        }
        if($updatecount > 0){
            $message .= "；更新: " . $updatecount . " 条";
        }
        if($skip > 0){
            $message .= "；跳过: " . $skip . " 条";
        }
        $this->success($message);
    }


    public function export()
    {
        $list = $this->model
            ->where('type',10)
            ->where('title','<>','')
            ->with(['biaobenType'])
            ->select();
        // 清除可能存在的输出缓冲
        if (ob_get_level()) {
            ob_end_clean();
        }
        // 创建新的Excel对象
        $spreadsheet = new Spreadsheet();
        // 获取当前活动工作表（默认创建第一个工作表）
        $sheet = $spreadsheet->getActiveSheet();
        // 给工作表命名
        $sheet->setTitle('项目数据');
        $sheet->setCellValue('A1', '项目名称');
        $sheet->setCellValue('B1', '项目简称');
        $sheet->setCellValue('C1', '项目拼音');
        $sheet->setCellValue('D1', '图片');
        $sheet->setCellValue('E1', '项目类型');
        $sheet->setCellValue('F1', '标本类型');
        $sheet->setCellValue('G1', '标本容器');
        $sheet->setCellValue('H1', '检测科室');
        $sheet->setCellValue('I1', '检测方法');
        $sheet->setCellValue('J1', '外检项目');
        $sheet->setCellValue('K1', '外检医院');
        $sheet->setCellValue('L1', '检测时长');
        $sheet->setCellValue('M1', '项目费用');
        $sheet->setCellValue('N1', '项目成本');
        $sheet->setCellValue('O1', '唯一编号');

        for ($i = 0; $i < count($list); $i++) {
            $row = $list[$i];
            $goods_category = \app\admin\model\goods\GoodsCategory::where('id','in',$row['goods_category_id'])->column('title');
            $biaoben_rongqi = \app\admin\model\goods\BiaobenRongqi::where('id','in',$row['biaoben_rongqi_id'])->column('title');
            $sheet->setCellValue('A' . ($i + 2), $row['title']);
            $sheet->setCellValue('B' . ($i + 2), $row['short_title']);
            $sheet->setCellValue('C' . ($i + 2), $row['pinyin_title']);
            $sheet->setCellValue('D' . ($i + 2), $row['image']);
            $sheet->setCellValue('E' . ($i + 2), implode(',',$goods_category));
            $sheet->setCellValue('F' . ($i + 2), !empty($row['biaoben_type']) ? $row['biaoben_type']['title'] : '');
            $sheet->setCellValue('G' . ($i + 2),implode(',',$biaoben_rongqi));
            $sheet->setCellValue('H' . ($i + 2), $row['keshi']);
            $sheet->setCellValue('I' . ($i + 2), $row['fangfa']);
            $sheet->setCellValue('J' . ($i + 2), $row['waijian_tags']);
            $sheet->setCellValue('K' . ($i + 2), $row['hospital']);
            $sheet->setCellValue('L' . ($i + 2), $row['time']);
            $sheet->setCellValue('M' . ($i + 2), $row['price']);
            $sheet->setCellValue('N' . ($i + 2), $row['original_price']);
            $sheet->setCellValue('O' . ($i + 2), $row['goods_no']);
        }
        

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="项目数据.xlsx"');
        header('Cache-Control: max-age=0');
        // 禁止缓存（可选，针对 IE）
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');


        $writer = new XlsxWriter($spreadsheet);
        // 输出到浏览器
        $writer->save('php://output');
        exit;
    }


}
